package com.gxg.newdemo1.mynewdamo1.channel;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.gxg.newdemo1.mynewdamo1.BaseApplication;
import com.gxg.newdemo1.mynewdamo1.R;
import com.gxg.newdemo1.mynewdamo1.channel.adapter.DragAdapter;
import com.gxg.newdemo1.mynewdamo1.channel.adapter.OtherAdapter;
import com.gxg.newdemo1.mynewdamo1.channel.bean.ChannelItem;
import com.gxg.newdemo1.mynewdamo1.channel.bean.ChannelManage;
import com.gxg.newdemo1.mynewdamo1.channel.view.DragGrid;
import com.gxg.newdemo1.mynewdamo1.channel.view.OtherGridView;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by uctimes on 2016/9/8.
 */
public class ChannelActivity extends Activity implements AdapterView.OnItemClickListener {


    public String TAG = "ChannelActivity";
    @BindView(R.id.kexuanchnnel)
    RadioButton kexuanchnnel;
    @BindView(R.id.citychannel)
    RadioButton citychannel;
    @BindView(R.id.group)
    RadioGroup group;
    @BindView(R.id.complete)
    TextView complete;
    @BindView(R.id.subscribe_main_layout)
    LinearLayout subscribeMainLayout;
    @BindView(R.id.back_text)
    TextView backText;
    /**
     * 用户栏目的GRIDVIEW
     */
    private DragGrid userGridView;
    /**
     * 其它栏目的GRIDVIEW
     */
    private OtherGridView otherGridView;
    /**
     * 用户栏目对应的适配器，可以拖动
     */
    DragAdapter userAdapter;
    /**
     * 其它栏目对应的适配器
     */
    OtherAdapter otherAdapter;
    /**
     * 其它栏目列表
     */
    ArrayList<ChannelItem> otherChannelList = new ArrayList<ChannelItem>();
    /**
     * 用户栏目列表
     */
    ArrayList<ChannelItem> userChannelList = new ArrayList<ChannelItem>();
    /**
     * 是否在移动，由于这边是动画结束后才进行的数据更替，设置这个限制为了避免操作太频繁造成的数据错乱。
     */
    boolean isMove = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_channel);
        ButterKnife.bind(this);
        setTitle("栏目管理");


        initView();
        initData();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backText.performClick();
        }
        return false;
    }

    /**
     * 初始化数据
     */
    private void initData() {
        userChannelList = ((ArrayList<ChannelItem>) ChannelManage.getManage(BaseApplication.getInstance().getSQLHelper()).getUserChannel());
        otherChannelList = ((ArrayList<ChannelItem>) ChannelManage.getManage(BaseApplication.getInstance().getSQLHelper()).getOtherChannel());
        int i = 0;
        for(ChannelItem c:userChannelList){
            if(c.getIschange()==2){
                i++;
            }
        }
        userGridView.setNoOnItemCliclister(i);
        userAdapter = new DragAdapter(this, userChannelList);
        userGridView.setAdapter(userAdapter);
        otherAdapter = new OtherAdapter(this, otherChannelList);
        otherGridView.setAdapter(otherAdapter);
//        AppManager.BaseActivity.setGridViewHeightBasedOnChildren(otherGridView, 4);
        //设置GRIDVIEW的ITEM的点击监听
        otherGridView.setOnItemClickListener(this);
        userGridView.setOnItemClickListener(this);
        backText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
//                Intent intent = new Intent(ChannelActivity.this, Main2Activity.class);
//                intent.putExtra("flag", "flag");
//                startActivity(intent);
//                finish();
            }
        });

        complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveChannel();
                finish();
//                Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
//                intent.putExtra("flag", "flag");
//                startActivity(intent);
//                finish();
//                overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
//
//
//                if (StringUtils.isEquals(SPUtils.get(ChannelActivity.this, "admin", "0").toString(), "0")) {
//                    return;
//                }
                updateItem();

            }
        });

    }

    /**
     * 初始化布局
     */
    private void initView() {
        userGridView = (DragGrid) findViewById(R.id.userGridView);
        otherGridView = (OtherGridView) findViewById(R.id.otherGridView);
    }

    /**
     * GRIDVIEW对应的ITEM点击监听接口
     */
    @Override
    public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
        //如果点击的时候，之前动画还没结束，那么就让点击事件无效
        if (isMove) {
            return;
        }
        switch (parent.getId()) {
            case R.id.userGridView:
                //position为 0，1 的不可以进行任何操作

                if(userChannelList.get(position).getIschange()!=2){
//                if ((!userChannelList.get(position).getName().equals("头条")) && !userChannelList.get(position).getName().equals("吉林") && !userChannelList.get(position).getName().equals("政情") && !userChannelList.get(position).getName().equals("读报") && !userChannelList.get(position).getName().equals("城市")) {
//                    if (position != 0 && position != 1&&position!=2&&position!=3&&position!=4) {
                    final ImageView moveImageView = getView(view);
//                    ToastUtils.toastL("Gridview长按事件",ChannelActivity.this);
//                    userAdapter.setImageShow(true);
                    if (moveImageView != null) {
                        TextView newTextView = (TextView) view.findViewById(R.id.text_item);
                        final int[] startLocation = new int[2];
                        newTextView.getLocationInWindow(startLocation);
                        final ChannelItem channel = ((DragAdapter) parent.getAdapter()).getItem(position);//获取点击的频道内容
                        otherAdapter.setVisible(false);

                        //添加到最后一个
                        otherAdapter.addItem(channel);
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                try {
                                    int[] endLocation = new int[2];
                                    //获取终点的坐标
                                    otherGridView.getChildAt(otherGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
                                    userAdapter.setRemove(position);
                                    MoveAnim(moveImageView, startLocation, endLocation, channel, userGridView,position);

                                } catch (Exception localException) {
                                }
                            }
                        }, 50L);
                    }
                }
                break;
            case R.id.otherGridView:
                final ImageView moveImageView = getView(view);
                if (moveImageView != null) {
                    TextView newTextView = (TextView) view.findViewById(R.id.text_item);
                    final int[] startLocation = new int[2];
                    newTextView.getLocationInWindow(startLocation);
                    Log.d("other", "onItemClick:11111 "+position);
                    final ChannelItem channel = ((OtherAdapter) parent.getAdapter()).getItem(position);
                    userAdapter.setVisible(false);
                    //添加到最后一个
                    userAdapter.addItem(channel);
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            try {
                                int[] endLocation = new int[2];
                                //获取终点的坐标
                                userGridView.getChildAt(userGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);

                                MoveAnim(moveImageView, startLocation, endLocation, channel, otherGridView,position);
                                Log.d("other", "onItemClick: 2222"+position);
                                otherAdapter.setRemove(position);
                            } catch (Exception localException) {
                            }
                        }
                    }, 50L);
                }
                break;
            default:
                break;
        }
    }


    /**
     * 点击ITEM移动动画
     *
     * @param moveView
     * @param startLocation
     * @param endLocation
     * @param moveChannel
     * @param clickGridView
     */
    private void MoveAnim(View moveView, int[] startLocation, int[] endLocation, final ChannelItem moveChannel,
                          final GridView clickGridView, final int pos) {
        int[] initLocation = new int[2];
        //获取传递过来的VIEW的坐标
        moveView.getLocationInWindow(initLocation);
        //得到要移动的VIEW,并放入对应的容器中
        final ViewGroup moveViewGroup = getMoveViewGroup();
        final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);
        //创建移动动画
        TranslateAnimation moveAnimation = new TranslateAnimation(
                startLocation[0], endLocation[0], startLocation[1],
                endLocation[1]);
        moveAnimation.setDuration(300L);//动画时间
        //动画配置
        AnimationSet moveAnimationSet = new AnimationSet(true);
        moveAnimationSet.setFillAfter(false);//动画效果执行完毕后，View对象不保留在终止的位置
        moveAnimationSet.addAnimation(moveAnimation);
        mMoveView.startAnimation(moveAnimationSet);
        moveAnimationSet.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                isMove = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                moveViewGroup.removeView(mMoveView);
                // instanceof 方法判断2边实例是不是一样，判断点击的是DragGrid还是OtherGridView
                if (clickGridView instanceof DragGrid) {
                    otherAdapter.setVisible(true);
                    otherAdapter.notifyDataSetChanged();
                    userAdapter.remove(pos);
                } else {
                    userAdapter.setVisible(true);
                    userAdapter.notifyDataSetChanged();
                    otherAdapter.remove(pos);
                }
                isMove = false;
            }
        });
    }

    /**
     * 获取移动的VIEW，放入对应ViewGroup布局容器
     *
     * @param viewGroup
     * @param view
     * @param initLocation
     * @return
     */
    private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {
        int x = initLocation[0];
        int y = initLocation[1];
        viewGroup.addView(view);
        LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mLayoutParams.leftMargin = x;
        mLayoutParams.topMargin = y;
        view.setLayoutParams(mLayoutParams);
        return view;
    }

    /**
     * 创建移动的ITEM对应的ViewGroup布局容器
     */
    private ViewGroup getMoveViewGroup() {
        ViewGroup moveViewGroup = (ViewGroup) getWindow().getDecorView();
        LinearLayout moveLinearLayout = new LinearLayout(this);
        moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        moveViewGroup.addView(moveLinearLayout);
        return moveLinearLayout;
    }

    /**
     * 获取点击的Item的对应View，
     *
     * @param view
     * @return
     */
    private ImageView getView(View view) {
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(true);
        Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
        ImageView iv = new ImageView(this);
        iv.setImageBitmap(cache);
        return iv;
    }

    /**
     * 退出时候保存选择后数据库的设置
     */
    private void saveChannel() {
        ChannelManage.getManage(BaseApplication.getInstance().getSQLHelper()).deleteAllChannel();

        /**
         * 把所有变成常用的栏目的uad都设置为1;
         * */
        int count = userAdapter.getChannnelLst().size();
        for (int i = 0; i < count; i++) {
            userAdapter.getChannnelLst().get(i).setUad(1);
        }

        /**
         * 把所有变成不常用的栏目的uad都设置为1;
         * */
        int length = otherAdapter.getChannnelLst().size();
        for (int i = 0; i < length; i++) {
            otherAdapter.getChannnelLst().get(i).setUad(2);
        }
        ChannelManage.getManage(BaseApplication.getInstance().getSQLHelper()).saveUserChannel(userAdapter.getChannnelLst());
        ChannelManage.getManage(BaseApplication.getInstance().getSQLHelper()).saveOtherChannel(otherAdapter.getChannnelLst());
    }

    @Override
    public void onBackPressed() {
        saveChannel();
//        if (userAdapter.isListChanged()) {
//            Intent intent = new Intent(getApplicationContext(), NewsFragment.class);
//            intent.putExtra("flag", "flag");
//            setResult(NewsFragment.CHANNELRESULT, intent);
//            finish();
//            Log.d(TAG, "数据发生改变");
//        } else {
//            super.onBackPressed();
//        }
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }

    private void updateItem() {

        /**
         * 首先新建一个数组，用来放所有的数据
         * 然后把常用的和不常用的和在一个数组里
         * */
        List<ChannelItem> list = new ArrayList<>();
        //常用
        int count = userAdapter.getChannnelLst().size();
        for (int i = 0; i < count; i++) {
            ChannelItem userChanneBean = userAdapter.getChannnelLst().get(i);
            ChannelItem bean = new ChannelItem();
            bean.setRid(userChanneBean.getRid());
            bean.setUad(userChanneBean.getUad());
            bean.setName(userChanneBean.getName());
            bean.setIschange(userChanneBean.getIschange());
            list.add(bean);
        }

        //不常用
        int length = otherAdapter.getChannnelLst().size();
        for (int i = 0; i < length; i++) {
            ChannelItem otherList = otherAdapter.getChannnelLst().get(i);
            ChannelItem bean = new ChannelItem();
            bean.setRid(otherList.getRid());
            bean.setUad(otherList.getUad());
            bean.setName(otherList.getName());
            bean.setIschange(otherList.getIschange());
            list.add(bean);

        }
        try {
            JSONObject body = new JSONObject();
            JSONArray array = new JSONArray();
            for (int i = 0; i < list.size(); i++) {
                //判断如果是不可以改变的，背景是红色的就不添加；
                if (list.get(i).getIschange() != 2) {
                    JSONObject childObj = new JSONObject();
                    childObj.put("id", list.get(i).rid);
                    childObj.put("order", list.size()-i);
                    childObj.put("uad", list.get(i).uad);
                    array.put(childObj);
                    Log.e("cccc", "栏目名称" + list.get(i).getName() + "  ;栏目uad:" + list.get(i).getUad() + "    ;栏目顺序：" + (list.size()-i));
                }
            }

//            body.put("loginname", SPUtils.get(ChannelActivity.this, "admin", "0"));
//            body.put("list", array);
//            new BaseRequest(ChannelActivity.this).doRequest_other(ChannelActivity.this, "AD1002", body, Urls.HOST, new StringCallback() {
//                @Override
//                public void onError(Call call, Exception e, int id) {
//
//                }
//
//                @Override
//                public void onResponse(String response, int id) {
//                    try {
//                        MainBean bean = GsonUtil.GsonToBean(response, MainBean.class);
//                        String canshu = SecurityUtil.decode3DES(bean.body, SPUtils.get(ChannelActivity.this, "key", "").toString());
//                        JSONObject mainObject = new JSONObject(canshu);
//                        KLog.json(canshu);
//                        SPUtils.put(ChannelActivity.this, "token", mainObject.getString("token"));
//
//                        if (StringUtils.isEquals(bean.header.error, "0000")) {
//                            ToastUtils.toastS("修改成功", ChannelActivity.this);
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//
//                }
//            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


}
